package com.example.practice;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;


import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;


/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_Busq extends Fragment {
    private View view;
    private int s=0;
    private ListView eee;
    private TextView heJi;
    private TextView cznl;
    private Button xiangQing;
    private ExpandableListView expendablelistview;
    private List<String> listG1 = new ArrayList<>();
    private List<Car4Users> list;
    private TimerTask timerTask;
    private Timer timer;
    private ExpandableListViewAdapter expandableListViewAdapter;
    public Fragment_Busq() {
        // Required empty public constructor
    }
    private interface Blogclient {
        @POST("pubcar")
        Call<ResponseBody> Blog(@Body RequestBody str);
    }
    private interface Blogsever {
        @GET("getCarPersonNum")
        Call<ResponseBody> Blog();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view=inflater.inflate(R.layout.fragment__busq, container, false);
        timer=new Timer();
        timerTask=new TimerTask(){
            @Override
            public void run() {
                list = new ArrayList<>();
                Map<String,Integer> map= new HashMap<>();
                map.put("CarId",0);
                String s1 = new Gson().toJson(map);
                initData(s1);
                map= new HashMap<>();
                map.put("CarId",1);
                String s2 = new Gson().toJson(map);
                initData(s2);
                if(s==1){
                    initData1();
                }

            }
        };
        timer.schedule(timerTask,0,3000);
        initView();
        return view;
    }

    private void initView() {
        cznl=view.findViewById(R.id.cznl);
        xiangQing=view.findViewById(R.id.xiangQing);
        xiangQing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                LayoutInflater layoutInflater = LayoutInflater.from(getContext());
                final View longinDialogView= layoutInflater.inflate(R.layout.list_busss, null);//找到定义的布局
                builder.setView(longinDialogView);//设置布局
                eee = (ListView) longinDialogView.findViewById(R.id.eee);
                heJi = (TextView) longinDialogView.findViewById(R.id.heJi);
                Button fh = (Button) longinDialogView.findViewById(R.id.fh);
                s=1;
                initData1();
                builder.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
                final AlertDialog dialog = builder.create();  //创建对话框
                dialog.setCanceledOnTouchOutside(true); //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
                dialog.show();//展示Alert
                fh.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
            }
        });
        expendablelistview=view.findViewById(R.id.expendablelistview);
        listG1.add("中医院站");
        listG1.add("联想大厦站");

    }
    private void initData1(){
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Blogsever blogsever = retrofit1.create(Blogsever.class);
        Call<ResponseBody> blog = blogsever.Blog();
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String ss = response.body().string();
                    List<Car5Users> list = new ArrayList<>();
                    Gson gson=new Gson();
                    Car5Users car5Users = gson.fromJson(ss,Car5Users.class);
                    list.add(car5Users);
                    eee.setAdapter(new Adapter(list));
                    int j =0;
                    for (int i=0;i<list.get(0).getData().size();i++){
                        int d =list.get(0).getData().get(i).getPersonNum();
                        j=j+d;
                    }
                    heJi.setText(j+"");
                    cznl.setText("当前承载能力："+j+"人");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
    private void initData(String s){
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Blogclient blogsever = retrofit1.create(Blogclient.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),s);
        Call<ResponseBody> blog = blogsever.Blog(requestBody);
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String ss = null;
                try {
                    ss = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Gson gson=new Gson();
                Car4Users car4Users = gson.fromJson(ss,Car4Users.class);
                list.add(car4Users);
                Collections.sort(list.get(0).getData(), new Comparator<Car4Users.DataBean>() {
                    @Override
                    public int compare(Car4Users.DataBean dataBean, Car4Users.DataBean t1) {
                        return (int)(dataBean.getDistance()*1000)-(int)(t1.getDistance()*1000);
                    }
                });
                if(list.size()==2 && expandableListViewAdapter != null) {
                    expandableListViewAdapter.updateData(list);
                    if (expendablelistview.collapseGroup(0))
                        expendablelistview.expandGroup(0);
                    if (expendablelistview.collapseGroup(1))
                        expendablelistview.expandGroup(1);
                }

                if(list.size()==2 && expandableListViewAdapter == null){
                    expandableListViewAdapter = new ExpandableListViewAdapter(listG1,list);
                    expendablelistview.setAdapter(expandableListViewAdapter);
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    private class ExpandableListViewAdapter extends BaseExpandableListAdapter {
        List<String> listG;
        List<Car4Users> listC;

        public ExpandableListViewAdapter(List<String> listG,List<Car4Users> listC) {
            this.listG= listG;
            this.listC= listC;
        }

        @Override
        public int getGroupCount() {
            return listG.size() ;
        }

        @Override
        public int getChildrenCount(int i) {
            return listC.size();
        }

        @Override
        public Object getGroup(int i) {
            return listG.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            return listC.get(i).getData().get(i1);
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return i1;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
            View inflate = View.inflate(getContext(), R.layout.list_bus, null);
            TextView textView = inflate.findViewById(R.id.textView1);
            textView.setText(listG.get(i));

            return inflate;
        }

        @Override
        public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
            View inflate = View.inflate(getContext(), R.layout.table_bus, null);
            TextView textView1=inflate.findViewById(R.id.id1);
            TextView textView2=inflate.findViewById(R.id.persons1);
            TextView textView3=inflate.findViewById(R.id.direction1);
            Log.v("TAG","eeeeee4"+listC.get(0).getData().get(i).getBus()+""+i);
            textView1.setText(listC.get(i).getData().get(i1).getBus()+"号 (101人) ");
            textView2.setText((int)((listC.get(i).getData().get(i1).getDistance()/20)*60)+"分钟到达");
            textView3.setText("距离站台"+(int)(listC.get(i).getData().get(i1).getDistance()*1000)+"米");
            return inflate;
        }
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return false;
        }
        void updateData(List<Car4Users> pubcarList){
            this.listC = pubcarList;
        }
    }
    private class Adapter extends BaseAdapter{
        List<Car5Users> list;
        public Adapter(List<Car5Users> list) {
            this.list=list;
        }

        @Override
        public int getCount() {
            return list.get(0).getData().size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View view1 = View.inflate(getContext(),R.layout.list_bussss,null);
            TextView t1 = view1.findViewById(R.id.eee1);
            TextView t2 = view1.findViewById(R.id.eee2);
            TextView t3 = view1.findViewById(R.id.eee3);
            t1.setText(i+1+"");
            t2.setText(list.get(0).getData().get(i).getCarId()+"");
            t3.setText(list.get(0).getData().get(i).getPersonNum()+"");
            return view1;
        }
    }
}
